<template>
  <!-- 动火安全作业票申请 -->
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelPosition="top">
        <view class="hidden-title">信息填写</view>
        <cu-cell-group>
          <cu-cell title="特殊作业类型：" :description="formData.workTypeLabel" description-align="right"></cu-cell>
          <uni-forms-item name="operationPoint">
            <cu-cell title="作业点" required>
              <input
                type="text"
                v-model="formData.operationPoint"
                placeholder="请输入(限20字)"
                class="input"
                placeholder-class="input-placeholder"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="unitName">
            <cu-cell
              :title="formData.workTypeFlag === specialWorkTypeEnum.ELECTRIC ? '用电单位' : '作业单位'"
              required
              link
              placeholder="请选择"
              :description="formData.unitName"
              @click="showDept()"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="directorName">
            <cu-cell
              :title="formData.workTypeFlag === specialWorkTypeEnum.ELECTRIC ? '用电单位负责人' : '作业单位负责人'"
              required
              link
              placeholder="请选择"
              :description="formData.directorName"
              @click="showUserSelector('director')"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="workContent">
            <cu-cell title="作业内容" column required>
              <uni-easyinput
                type="textarea"
                v-model="formData.workContent"
                placeholder="请输入(限50字)"
                maxlength="50"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="riskIdentificationResult">
            <cu-cell
              title="风险辨识结果"
              required
              link
              placeholder="请选择"
              :description="formData.riskIdentificationResult"
              @click="showRiskResult()"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="safetyMeasure">
            <cu-cell
              title="安全措施"
              required
              link
              placeholder="请选择"
              :description="formData.safetyMeasure"
              @click="showMeasure()"
            ></cu-cell>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>
      <component
        ref="ticketComp"
        v-bind:is="currentTicketComponent"
        :ticket-info="ticketFormData || {}"
        :unit-id="formData.unitId"
        :node-list="nodeAttrs"
        :proc-def-id="procDefId"
        :template-id="templateId"
        @on-level-change="onLevelChange"
      />

      <cu-cell-group>
        <uni-forms-item>
          <cu-cell
            title="电子围栏"
            link
            :description="formData.electronicFenceCoordinates.length ? '已绘制' : '未绘制'"
            @click="handleFence()"
          ></cu-cell>
        </uni-forms-item>
      </cu-cell-group>
      <!--      <view v-if="formData.electronicFenceImage">-->
      <!--        <image style="width: 100vw;" :src="staticUrl + formData.electronicFenceImage" mode="widthFix"></image>-->
      <!--      </view>-->
      <view v-if="nodeAttrs.length">
        <view class="hidden-title">预设审批人</view>
        <cu-cell-group>
          <uni-forms-item name="name" v-for="(node, index) in nodeAttrs" :key="node.nodeId">
            <!--单选-->
            <cu-cell
              v-show="nodeVisibleFunc(node)"
              :title="node.formTitle"
              :placeholder="node.name"
              required
              @click="handleChooseApplyUser(node, index)"
              :description="descriptionFormat(node)"
              link
            >
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
      </view>

      <view class="button-wrap">
        <view class="submit-button" @click="submit">保存</view>
      </view>
    </view>

    <!--作业单位类型-->
    <dept-selector ref="deptSelectorRef" @change="unitConfirm"></dept-selector>

    <!--作业单位-->
    <data-picker
      ref="contractorRef"
      title=""
      label-key="name"
      value-key="id"
      :data="contractorList"
      @confirm="contractorConfirm"
    ></data-picker>

    <!-- 用户选择器 v2 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :checkList="deptUserSelectProps.checkList"
      :dept-id="deptUserSelectProps.deptId"
      :multiple="deptUserSelectProps.multiple"
      :autoRequestUser="deptUserSelectProps.autoRequestUser"
      :deptRequestApi="deptUserSelectProps.deptRequestApi"
      :userRequestApi="deptUserSelectProps.userRequestApi"
      @change="onDeptUserChange"
    ></cu-dept-user-select>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellMultiLine from '@/components/cu-cell/cu-cell-multi-line.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import CuSelect from '@/components/cu-select/cu-select.vue'
import DeptSelector from '@/components/dept-selector/index.vue'
import UserSelector from '@/components/user-selector/index.vue'
import DataPicker from '@/components/data-picker/index.vue'

import ticketMixin from './ticketMixin.js'

import FireTicketApply from './fire-ticket-apply.vue'
import LimitSpaceTicketApply from './limit-space-ticket-apply.vue'
import BlindPlateTicketApply from './blind-plate-ticket-apply.vue'
import HighTicketApply from './high-ticket-apply.vue'
import LiftingTicketApply from './lifting-ticket-apply.vue'
import ElectricTicketApply from './electric-ticket-apply.vue'
import BreakerTicketApply from './breaker-ticket-apply.vue'
import BreakGroundTicketApply from './break-ground-ticket-apply.vue'
import DeviceOverhaulApply from './device-overhaul-apply.vue'
import { specialWorkTypeEnum } from '@/utils/constant'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import { staticUrl } from '@/config'

export default {
  mixins: [ticketMixin],
  components: {
    CuDeptUserSelect,
    CuCellGroup,
    CuCell,
    CuCellMultiLine,
    CuSelect,
    DictPicker,
    UserSelector,
    DataPicker,
    DeptSelector,
    FireTicketApply,
    LimitSpaceTicketApply,
    BlindPlateTicketApply,
    HighTicketApply,
    LiftingTicketApply,
    ElectricTicketApply,
    BreakGroundTicketApply,
    BreakerTicketApply,
    DeviceOverhaulApply
  },
  onBackPress(options) {
    if (options.from === 'backbutton') {
      this.$modal.confirm(`当前填写的内容不会保存，确认返回？`).then(() => {
        uni.navigateBack()
      })
      return true
    }
  },
  onReady() {},
  computed: {
    staticUrl() {
      return staticUrl
    },
    specialWorkTypeEnum() {
      return specialWorkTypeEnum
    },
    currentTicketComponent() {
      return this.comps[this.formData.workTypeFlag].componentName
    }
  },
  mounted() {},
  data() {
    return {
      groupUsers: [],
      deptUserSelectProps: {
        deptId: '',
        checkList: [],
        multiple: false,
        deptRequestApi: null,
        userRequestApi: null,
        autoRequestUser: false
      },
      comps: {
        FIRE: { name: '动火', componentName: 'FireTicketApply' },
        CONFINED_SPACE: { name: '受限空间', componentName: 'LimitSpaceTicketApply' },
        BLIND_PLATE_PLUGGING: { name: '盲板抽堵', componentName: 'BlindPlateTicketApply' },
        ELEVATION: { name: '高处作业', componentName: 'HighTicketApply' },
        HOISTING: { name: '吊装', componentName: 'LiftingTicketApply' },
        TEMP_ELECTRICITY: { name: '临时用电', componentName: 'ElectricTicketApply' },
        BREAK_GROUND: { name: '动土', componentName: 'BreakGroundTicketApply' },
        OPEN_CIRCUIT_SAFETY: { name: '断路', componentName: 'BreakerTicketApply' },
        EQUIPMENT_SAFETY: { name: '设备检修', componentName: 'DeviceOverhaulApply' }
      },
      checkList: [],
      template: {},
      ticketData: {},
      formData: {
        areaId: '',
        areaName: '',
        workTypeFlag: '',
        workTypeLabel: '',
        workContent: '', // 作业内容
        operationPoint: '', // 作业地点
        unitType: '',
        unitId: '',
        unitName: '',
        directorId: '',
        directorName: '',
        riskIdentificationResult: '',
        riskIdentificationArr: [],
        safetyMeasureContent: '',
        safetyMeasure: '',
        safetyMeas: '',
        electronicFenceImage: '', // 电子围栏图片
        electronicFenceCoordinates: [], // 电子围栏区域坐标
        electronicFenceExtrudeHeight: 0, // 电子围栏基底高度
        electronicFenceHeight: 20 // 电子围栏高度
      },
      contractorList: [],
      selectUserType: 1,
      ticketFormData: {},
      rules: {
        operationPoint: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        unitName: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        directorName: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workContent: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        riskIdentificationResult: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        safetyMeasure: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },

  methods: {
    nodeVisibleFunc(node) {
      const level = this.ticketWorkLevel
      const { defaultAssignee, assignCondition } = node
      if (defaultAssignee === 0) {
        // 判断表达式
        let expression = ''
        // 节点审批人员条件
        if (assignCondition) {
          const regex = /\${(.*?)\}/
          expression = assignCondition.match(regex)[1]
        }
        if (expression) {
          return eval(expression)
        } else {
          return true
        }
      } else {
        return false
      }
    },
    onLevelChange(val) {
      this.ticketWorkLevel = val
    },
    deptRequestApi() {
      return new Promise((resolve, reject) => {
        resolve({
          data: []
        })
      })
    },
    requestApi(params) {
      console.log('params', params)
      const keyword = params.keyword.trim()
      if (keyword) {
        return new Promise((resolve) => {
          resolve({
            rows: this.groupUsers.filter((item) => item.name.indexOf(keyword) > -1),
            total: 0 // 给0免得触发上拉加载，数据扛不住再说，累人
          })
        })
      }
      return new Promise((resolve) => {
        resolve({
          rows: this.groupUsers,
          total: 0 // 给0免得触发上拉加载，数据扛不住再说，累人
        })
      })
    },
    // 审批节点选择用户
    handleChooseApplyUser(node, index) {
      this.selectUserType = 'workflow'
      this.nodeIndex = index // 当前选择的节点索引
      this.deptUserSelectProps.checkList = JSON.parse(JSON.stringify(node.staffs ?? []))
      this.deptUserSelectProps.multiple = node.attribute.execType !== 'SINGLE'
      this.deptUserSelectProps.deptId = ''
      if (node.personData.reviewerElectType === 'USER_GROUP') {
        this.groupUsers = node.personData.users
        this.deptUserSelectProps.deptRequestApi = this.deptRequestApi
        this.deptUserSelectProps.userRequestApi = this.requestApi
        this.deptUserSelectProps.autoRequestUser = true
      } else {
        this.deptUserSelectProps.deptRequestApi = null
        this.deptUserSelectProps.userRequestApi = null
        this.deptUserSelectProps.autoRequestUser = false
      }
      this.$refs.deptUserSelectRef.open()
    },
    onDeptUserChange(val) {
      switch (this.selectUserType) {
        // 审批节点
        case 'workflow':
          this.$set(this.nodeAttrs[this.nodeIndex], 'staffs', val ?? [])
          break
        // 作业负责人
        case 'director':
          this.formData.directorId = val[0].userId
          this.formData.directorName = val[0].name
          break
        default:
          break
      }
    },
    descriptionFormat(node) {
      const staffs = node.staffs ?? []
      const desc = []
      const max = staffs.length > 2 ? 2 : staffs.length
      for (let i = 0; i < max; i++) {
        desc.push(staffs[i].name)
      }
      const descStr = staffs.length > 2 ? desc.join('、') + `等${staffs.length}人` : desc.join('、')
      return descStr
    },
    contractorConfirm(obj) {
      this.formData.unitId = obj.value
      this.formData.unitName = obj.name
      this.formData.directorId = ''
      this.formData.directorName = ''
    },
    showDept() {
      this.$refs.deptSelectorRef.open()
    },
    unitConfirm({ name, value, property }) {
      this.formData.unitId = value
      this.formData.unitName = name
      this.formData.unitType = property
      this.formData.directorId = ''
      this.formData.directorName = ''
    },
    showUserSelector(type) {
      this.selectUserType = type
      if (this.formData.unitName === '') {
        this.$modal.showToast('请先选择作业单位')
        return
      }

      this.deptUserSelectProps.checkList = [{ userId: this.formData.directorId, name: this.formData.directorName }]
      this.deptUserSelectProps.multiple = false
      this.deptUserSelectProps.deptRequestApi = null
      this.deptUserSelectProps.userRequestApi = null
      this.deptUserSelectProps.autoRequestUser = true
      this.deptUserSelectProps.deptId = this.formData.unitId
      this.$refs.deptUserSelectRef.open()
    },
    showMeasure() {
      uni.navigateTo({
        url: '/pages/jobSlip/work-ticket/measures?workType=' + this.formData.workTypeFlag,
        events: {
          'measures:form:success': (data) => {
            console.log('measures:form', data)
            this.onMeasuresSuccess(data)
          }
        },
        success: (res) => {
          res.eventChannel.emit('measuresData', this.formData.safetyMeasureContent)
        }
      })
    },
    // 风险辨识结果
    showRiskResult() {
      uni.navigateTo({
        url: '/pages/jobSlip/work-ticket/risk-result',
        events: {
          'risk-result:form:success': (data) => {
            const types = data.reduce((risk, cur) => risk.concat(cur.riskType), [])
            this.formData.riskIdentificationResult = types.join(', ')
            this.formData.riskIdentificationArr = data
          }
        },
        success: (res) => {
          res.eventChannel.emit('riskResultData', this.formData.riskIdentificationArr)
        }
      })
    },
    onMeasuresSuccess(data) {
      if (data) {
        this.formData.safetyMeasure = '已确认'
        this.formData.safetyMeasureContent = data
      }
    },
    handleFence() {
      uni.navigateTo({
        url: '/pages/jobSlip/work-ticket/fence',
        success: (res) => {
          res.eventChannel.emit('fenceData', {
            electronicFenceImage: this.formData.electronicFenceImage, // 电子围栏图片
            electronicFenceCoordinates: this.formData.electronicFenceCoordinates, // 电子围栏区域坐标
            electronicFenceExtrudeHeight: this.formData.electronicFenceExtrudeHeight, // 电子围栏基底高度
            electronicFenceHeight: this.formData.electronicFenceHeight // 电子围栏高度
          })
        },
        events: {
          'fence:form:success': (data) => {
            this.formData.electronicFenceImage = data.image ?? ''
            this.formData.electronicFenceCoordinates = data.coordinates?.length ? data.coordinates[0] : [] // 电子围栏区域坐标
            this.formData.electronicFenceExtrudeHeight = data.extrudedHeight?.length ? data.extrudedHeight[0] : 0 // 电子围栏基底高度
            this.formData.electronicFenceHeight = data.height?.length ? data.height[0] : 20 // 电子围栏高度
            console.log('fence:form:success', this.formData)
          }
        }
      })
    },

    async submit() {
      await this.$refs.form.validate()
      await this.$refs.ticketComp.submit()

      if (this.formData.workTypeFlag === specialWorkTypeEnum.FIRE) {
        if (!this.$refs.ticketComp.certificateValidate()) {
          return
        }
      }
      const level = this.ticketWorkLevel
      let bool = false
      for (let i = 0; i < this.nodeAttrs.length; i++) {
        const { defaultAssignee, assignCondition, staffs } = this.nodeAttrs[i]
        const isEmpty = !staffs || staffs.length === 0
        // 节点存在 并且 不默认处理人节点 (1默认 0不默认)
        if (defaultAssignee === 0) {
          // 判断表达式
          let expression = ''
          // 节点审批人员条件
          if (assignCondition) {
            const regex = /\${(.*?)\}/
            expression = assignCondition.match(regex)[1]
          }

          if (expression) {
            if (isEmpty && eval(expression)) {
              bool = true
              break
            }
          } else {
            if (isEmpty) {
              bool = true
              break
            }
          }
        }
      }

      if (bool) {
        this.$modal.showToast('当前流程节点人员未配置完整')
        return
      }
      const staffs = []
      this.nodeAttrs.forEach((item) => {
        item.staffs.forEach((staff) => {
          staffs.push({
            maintainer: 1,
            nodeId: item.nodeId,
            userId: staff.staffId,
            userName: staff.staffName
          })
        })
      })
      this.formData.riskIdentification = JSON.stringify(this.formData.riskIdentificationArr)
      this.ticketFormData = this.$refs.ticketComp.result

      /*安全措施*/
      this.safetyMeas = JSON.stringify([
        ...this.formData.safetyMeasureContent.tableData,
        ...this.formData.safetyMeasureContent.otherData
      ])

      const result = {
        ...JSON.parse(JSON.stringify(this.ticketFormData)),
        ...this.formData,
        procDefId: this.procDefId,
        workType: this.ticketData.workTypeFlag,
        workId: this.ticketData.workId,
        ticketWorkLevelKey: 'spw_fire_work_level',
        safetyMeas: this.safetyMeas,
        staffs: staffs,
        nodeAttrs: JSON.parse(JSON.stringify(this.nodeAttrs))
      }
      console.log('result', result)
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('ticket:form:success', result)
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.button-wrap {
  padding: 20px 30px;
  display: flex;
  .space {
    width: 50rpx;
  }
  .submit-button,
  .draft-button {
    flex: 1;
    color: #ffffff;
    line-height: 88rpx;
    text-align: center;
    border-radius: 50rpx;
    font-size: 36rpx;
  }
  .submit-button {
    background: #454a5e;
  }

  .draft-button {
    background: #c4c088;
  }
}
.other-type {
  background: #f5f5f5;
  padding: 20rpx;
  margin-top: 10rpx;
  .input {
    text-align: left;
  }
}
.index {
  width: 15px;
}
.name {
  width: 15%;
}
.content {
  width: 60%;
}
</style>
